package Windows.DownLoads;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;

import Client.msgSend;
import GroupWare.DownloadTask;
import GroupWare.ShareRoot;
import XML.XMLNode;

public class ResDownTable extends JScrollPane implements MouseListener {
	public static void main(String args[]) {

//		ResDownTable rst = new ResDownTable(null,null);
//		JFrame f = new JFrame();
//		f.getContentPane().add(rst, BorderLayout.CENTER);
//		f.setTitle("TableEventHandle");
//		f.pack();
//		f.setVisible(true);
//		StringBuffer sb = new StringBuffer("2M/s");
//		Object[] objs = { "安全", "资源名称", "类型", "评论", "文件大小", "更新日期", sb,sb, sb,
//				"贡献者", "MD5" };
//		rst.mt.addRow(objs);
//		sb.append("!");
//		f.addWindowListener(new WindowAdapter() {
//			public void windowClosing(WindowEvent e) {
//				System.exit(0);
//			}
//		});
	}
	DownloadTableModel mt = new DownloadTableModel();
	JTable table = new JTable(mt);
	Date readyTime;
	msgSend send;
	Timer timer = new Timer();// 任务时钟
	TimerTask tt;
	private ArrayList<DownloadTask> aldf;// 下载任务
	JPopupMenu menu = new JPopupMenu();
	ArrayList<XMLNode> alxf = new ArrayList<XMLNode>(0);

	ShareRoot sp;

	public ResDownTable(msgSend send, ArrayList<DownloadTask> aldf, ShareRoot sp) {
		this.send = send;
		this.aldf = aldf;
		this.sp = sp;
		setViewportView(table);
		init();
		// TableColumn tc = table.getColumn("速度");
		table.setPreferredScrollableViewportSize(new Dimension(550, 30));
		readyTime = new Date();
		timer = new Timer();
		tt = new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				table.repaint();// 重新绘制
			}

		};
		timer.schedule(tt, 500, 500);
	}

	/**
	 * 新建一个任务
	 * 
	 * @param df
	 */
	public void addFile(DownloadTask df, XMLNode xf) {
		if (aldf.indexOf(df) != -1) {
			System.out.println("[新建重复任务]" + df);
			return;
		}
		aldf.add(df);
		alxf.add(xf);
		// --取资源文件全名
		String name = df.getF().getName();
		int j = name.lastIndexOf('.');
		// --取资源类型名
		String type = j != -1 ? name.substring(j, name.length()) : "未知";
		// --取资源名称
		name = j != -1 ? name.substring(0, j) : name;
		// --格式化文件更新日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long time = df.getLastModified();
		// 插入一行记录
//		Object[] obj = {"安全",name,type, "(256)",df.getSizeStr(),df.achieveStr,df.dAchieve,df.speedStr,df.resStr,sdf.format(new Date(time)),df.md5};
//		mt.addRow(obj);//添加一行
		table.updateUI();// 发出的表明 L&F 已经更改的通知。用 UIManager 的最新版本替换当前的 UI 对象。
		send.sendGetRes(df.md5);
		df.start();// 启动任务
	}

	public DownloadTask getSelectDF() {
		int i = getSelectRow();
		if (i == -1)
			return null;
		return aldf.get(i);
	}

	public int getSelectRow() {
		return table.getSelectedRow();
	}

	/**
	 * 去选中项的XML数据
	 * 
	 * @return
	 */
	public XMLNode getSelectXml() {
		int i = table.getSelectedRow();
		if (i == -1)
			return null;
		return alxf.get(i);
	}

	public void init() {
		RatioRenderer renderer = new RatioRenderer();
		renderer.setForeground(Color.BLUE);
		table.setDefaultRenderer(Dimension.class, renderer);

		JMenuItem opf = new JMenuItem("打开文件");
		JMenuItem opd = new JMenuItem("打开目录");
		JMenuItem dele = new JMenuItem("删除文件");
		JMenuItem down = new JMenuItem("重新下载");
		JMenuItem attribute = new JMenuItem("资源信息");
		JMenuItem comment = new JMenuItem("评论资源");
		menu.add(opf);
		menu.add(opd);
		menu.add(dele);
		menu.add(down);
		menu.add(attribute);
		menu.add(comment);

		// --注册事件监听器
		table.addMouseListener(this);
		Tools.TableStyle.setDefaultStyle(table);

		opf.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
//				xmlFlag xf = getSelectXml();
				int i = getSelectRow();
				if (i != -1) {
					aldf.get(i).open();// 打开文件
				}
			}
		});

		opd.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
//				xmlFlag xf = getSelectXml();
				int i = getSelectRow();
				if (i != -1) {
					aldf.get(i).openDir();// 打开文件
				}
			}
		});

		dele.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
//				xmlFlag xf = getSelectXml();
				int i = getSelectRow();
				if (i != -1) {
					int k = JOptionPane.showConfirmDialog(null, "您确认删除这个文件吗？");
					System.out.println(k);
					if (k == 0) {
						remove(i, aldf.get(i));// 打开文件
					}
				}
			}
		});
//		opd.addActionListener(new ActionListener(){
//
//			public void actionPerformed(ActionEvent arg0) {
//				// TODO Auto-generated method stub
////				xmlFlag xf = getSelectXml();
//				int i =getSelectRow();
//				if(i!=-1){
//					aldf.get(i).openDir();//打开文件
//				}
//			}});
//		opd.addActionListener(new ActionListener(){
//
//			
//			public void actionPerformed(ActionEvent arg0) {
//				// TODO Auto-generated method stub
////				xmlFlag xf = getSelectXml();
//				int i =getSelectRow();
//				if(i!=-1){
//					aldf.get(i).openDir();//打开文件
//				}
//			}});

	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent m) {
		// TODO Auto-generated method stub
//		System.out.println("下载表格:鼠标按钮释放，"+m.getButton());
		if (m.getButton() == 3 && this.getSelectRow() != -1) {
			menu.show(this, m.getX(), m.getY());
		}
	}

	/**
	 * 删除任务，包括集合中
	 */
	public void remove(int row, DownloadTask df) {
		mt.removeRow(row);
		aldf.remove(df);
		df.pause();// 停止任务
		df.getF().delete();// 删除文件
		sp.remove(df);
		table.updateUI();// 发出的表明 L&F 已经更改的通知。用 UIManager 的最新版本替换当前的 UI 对象。
//		System.out.println("[删除任务]row:"+row+"\tdf:"+df);
	}

	public void tableChanged(TableModelEvent e) {

	}

}
